package spring.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import spring.rabbitmq.User;
import spring.rabbitmq.producer.RabbitMqConfig;

/**
 * 消费者
 *
 * @author ZCW
 * @createTime 2018/4/28
 * @lastUpdateTime 2018/4/28 ZCW
 */
@Component
public class Consumer {

//    @RabbitListener(queues = RabbitMqConfig.HELLO)
    public void receiveHello(Object msg) throws InterruptedException {
        System.out.println("---------------receiveHello---------------");
        System.out.println(msg);
        System.out.println("---------------receiveHello---------------");
//        Thread.sleep(1000);  // 单线程消费
//        throw new RuntimeException(); // 抛出异常，消费失败
    }

    @RabbitListener(queues = RabbitMqConfig.OBJECT)
    public void receiveObject(User user) throws InterruptedException {
        System.out.println("---------------receiveObject---------------");
        System.out.println(JSON.toJSONString(user));
        System.out.println("---------------receiveObject---------------");
    }

//    @RabbitListener(queues = RabbitMqConfig.WORKQUEUES)
    public void receivWorkQueues(Message msg) throws Exception {
        System.out.println("---------------receivWorkQueues---------------");
        System.out.println(msg);

        // 模拟耗时业务
        String message = new String(msg.getBody(), "UTF-8");
        for (char ch: message.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }

        System.out.println("---------------receivWorkQueues---------------");
    }

}

